package com.dhecp.project.flowable.controller;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.poi.ExcelUtil;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.project.flowable.domain.ActProcessDefinition;
import com.dhecp.project.flowable.service.ActProcessDefinitionService;
import org.flowable.engine.repository.ProcessDefinition;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ProcessDefinitionController
 * @Description 流程定义 控制层
 * @Author alula
 * @Date 2019-11-27 9:16
 */
@Controller
@RequestMapping("/flowable/definition")
public class ActProcessDefinitionController extends BaseController {
    private String prefix = "flowable/definition";
    private String moduleTable = ModuleTable.ACT_RE_PROCDEF;

    @Autowired
    private ActProcessDefinitionService actProcessDefinitionService;
    
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;
    
    @RequiresPermissions("flowable:definition:view")
    @GetMapping()
    public ModelAndView processDefinition(@RequestParam Map<String, Object> params)
    {
    	params.put("moduleTable", moduleTable);
    	params.put("entity", new ActProcessDefinition());
        
    	Integer toolBarWidth = 350;
        params.put("toolBarWidth", toolBarWidth);
    	
    	ModelAndView mv = this.getModelAndView();
    	mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
    	mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", moduleTable);
    	mv.setViewName(prefix + "/definition");
		return mv;
    }

    @RequestMapping("/list")
    @RequiresPermissions("flowable:definition:list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        List<ActProcessDefinition> list = actProcessDefinitionService.queryProcessDefinitionList(params);
        return getDataTable(list);
    }

    /**
     * 部署流程定义
     */
    @RequiresPermissions("flowable:definition:add")
    @Log(title = "流程定义文件部署", businessType = BusinessType.INSERT)
    @RequestMapping("/deployByFile")
    @ResponseBody
    public AjaxResult deployByFile(@RequestParam("processDefinition") MultipartFile file) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                String extension = FilenameUtils.getExtension(fileName);
                if ("xml".equalsIgnoreCase(extension)) {
                    if (!file.getOriginalFilename().contains("bpmn20.xml")) {
                        return AjaxResult.error(MessageUtils.message("flowable.definition.error.uploadallowtype"));
                    }
                }
                if (!"xml".equalsIgnoreCase(extension)
                        && !"bpmn".equalsIgnoreCase(extension)
                        && !"zip".equalsIgnoreCase(extension)
                        && !"bar".equalsIgnoreCase(extension)) {
                    return AjaxResult.error(MessageUtils.message("flowable.definition.error.uploadallowtype"));
                }
                InputStream fileInputStream = file.getInputStream();
                ajaxResult = actProcessDefinitionService.deployProcessDefinition(fileInputStream, fileName);
                return  ajaxResult;
            }
            return AjaxResult.error(MessageUtils.message("module.error.iserror"));
        }
        catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

    @RequiresPermissions("flowable:definition:edit")
    @Log(title = "流程定义转模型", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/convertToModel")
    @ResponseBody
    public AjaxResult convertDefinitionToModel(String proDefId)
    {
        AjaxResult ajaxResult = new AjaxResult();
        try
        {
            ajaxResult = actProcessDefinitionService.convertProcessDefinitionToModel(proDefId);
            return ajaxResult;
        }
        catch (Exception e)
        {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

    @RequiresPermissions("flowable:definition:delete")
    @Log(title = "流程定义删除", businessType = BusinessType.DELETE)
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult deleteDefinition(@RequestParam("id") String id,
                                       @RequestParam("depId") String depId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = actProcessDefinitionService.deleteProcessDeploymentById(id, depId);
            return ajaxResult;
        }
        catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

    @Log(title = "流程定义导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("flowable:definition:export")
    @RequestMapping("/export")
    @ResponseBody
    public AjaxResult exportDefinition() {
        try {
            Map<String, Object> params = new HashMap<>();
            List<ActProcessDefinition> list = actProcessDefinitionService.queryProcessDefinitionList(params);
            ExcelUtil<ActProcessDefinition> util = new ExcelUtil<>(ActProcessDefinition.class);
            return util.exportExcel(list, "流程定义数据");
        } catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

    @RequiresPermissions("flowable:definition:edit")
    @Log(title = "流程定义更新状态", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult updateDefinitionStatus(@RequestParam String proDefId, @RequestParam Integer status){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = actProcessDefinitionService.updateProcessDefinitionStatus(proDefId, status);
            return ajaxResult;
        }
        catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

    //获取流程定义图片
    @RequestMapping("/flowsheetbykey")
    public ModelAndView flowsheetByKey(@RequestParam("procDefKey") String procDefKey) {
        ModelAndView modelAndView = this.getModelAndView();
        if (StringUtils.isEmpty(procDefKey)) {
            modelAndView.addObject("errorMessage", MessageUtils.message("module.error.paramfail", procDefKey));
            modelAndView.setViewName("error/business");
            return modelAndView;
        }
        ProcessDefinition processDefinition = actProcessDefinitionService.queryActProcessDefinitionByKey(procDefKey);
        if(processDefinition == null){
            modelAndView.addObject("errorMessage", MessageUtils.message("flowable.definition.error.defexistsfail"));
            modelAndView.setViewName("error/business");
            return modelAndView;
        }
        modelAndView.addObject("proDefId", processDefinition.getId());
        modelAndView.setViewName(prefix + "/flowsheet");
        return modelAndView;
    }

    //获取流程定义图片
    @RequestMapping("/flowsheetbyid")
    public ModelAndView flowsheetById(@RequestParam("procDefId") String procDefId) {
        ModelAndView modelAndView = this.getModelAndView();

        ProcessDefinition processDefinition = actProcessDefinitionService.queryActProcessDefinitionById(procDefId);
        if(processDefinition == null){
            modelAndView.addObject("errorMessage", MessageUtils.message("flowable.definition.error.defexistsfail"));
            modelAndView.setViewName("error/business");
            return modelAndView;
        }
        modelAndView.addObject("proDefId", processDefinition.getId());
        modelAndView.setViewName(prefix + "/flowsheet");
        return modelAndView;
    }

    @RequestMapping(value = "/getFlowsheet/{proDefId}", method = RequestMethod.GET)
    public void getFlowsheetResource(@PathVariable String proDefId,
                               HttpServletResponse response) throws Exception{
        ProcessDefinition processDefinition = actProcessDefinitionService.queryActProcessDefinitionById(proDefId);
        if(processDefinition == null){
            return;
        }
        String resourceName= processDefinition.getDiagramResourceName();
        InputStream inputStream = actProcessDefinitionService.getProcessDefinitionImage(processDefinition.getId(), processDefinition.getDeploymentId(), resourceName);
        if (inputStream != null) {
            // 设置页面不缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            inputStream.close();
        }
    }
}
